#!/usr/bin/python2.4


import urllib

import rpc_stubs
import utils


def make_url(default_dargs, ordered_keys, **dargs):

  def quote(data):
    return (data.replace('%', '%25').replace('&', '%26').
            replace('+', '%2B').replace('=', '%3D'))

  kv_dict = dict(default_dargs)
  utils.update_dict(kv_dict, dargs)
  base_url = kv_dict.pop('base_url', '')
  quoted_kv_pairs = []
  for key in ordered_keys:
    if key in kv_dict:
      quoted_kv_pairs.append((quote(key), quote(kv_dict.pop(key))))
  for key, value in kv_dict.iteritems():
    quoted_kv_pairs.append((quote(key), quote(value)))
  return '%s%s' % (base_url, urllib.urlencode(quoted_kv_pairs))


def afe_url(**dargs):
  default_dargs = {
      'base_url': 'http://%s/afe/#' % rpc_stubs.AUTOTEST_WEB,
  }
  ordered_keys = ('tab_id', 'object_id')
  return make_url(default_dargs, ordered_keys, **dargs)


def tko_url(**dargs):
  default_dargs = {
    'base_url': 'http://%s/new_tko/#' % rpc_stubs.AUTOTEST_WEB,
    'tab_id': 'spreadsheet_view',
    'row': 'hostname',
    'column': 'test_name',
    'show_incomplete': 'true',
    'show_only_latest': 'false',
    'show_invalid': 'false',
  }
  ordered_keys = ('tab_id', 'row', 'column', 'show_incomplete',
                  'show_only_latest', 'condition', 'show_invalid')
  return make_url(default_dargs, ordered_keys, **dargs)


def afe_host_url(hostname):
    return afe_url(tab_id='view_host', object_id=hostname)


def afe_job_url(job_id):
    return afe_url(tab_id='view_job', object_id=job_id)


def tko_job_tag_url(job_tags):
  if len(job_tags) == 1:
    condition = "job_tag = '%s'" % job_tags[0]
  else:
    condition = 'job_tag IN (%s)' % utils.quoted_array(job_tags)
  return tko_url(condition=condition, show_invalid='true')


def tko_job_host_runs_sql(job_host_runs, idx_getter):
  job_host_runs.sort(key=idx_getter)

  singles = []
  zero_uppers = []
  pairs = []

  def add(start, start_idx, end):
    if start_idx == 0 and end - start >= 3:
      zero_uppers.append(job_host_runs[end - 1].job_idx)
    elif end - start >= 5:
      pairs.append((job_host_runs[start].job_idx,
                    job_host_runs[end - 1].job_idx))
    else:
      singles.extend(job_host_runs[i].job_idx for i in xrange(start, end))

  start_idx = last_idx = -1
  start = -1
  for i, run in enumerate(job_host_runs):
    idx = idx_getter(run)
    if i == 0 or idx != last_idx + 1:
      if i:
        add(start, start_idx, i)
      start = i
      start_idx = idx
    last_idx = idx
  if start >= 0:
    add(start, start_idx, len(job_host_runs))

  or_list = []
  if len(singles) == 1:
    or_list.append('job_idx = %d' % singles[0])
  elif singles:
    or_list.append('job_idx IN (%s)' %
                   ', '.join(str(i) for i in singles))
  if zero_uppers:
    or_list += ('job_idx <= %d' % zero_upper for zero_upper in zero_uppers)
  if pairs:
    or_list += ('job_idx BETWEEN %d AND %d' % pair for pair in pairs)

  return ' OR '.join(or_list)


def autotest_log_url(job_tag):
  return 'http://%s/tko/retrieve_logs.cgi?job=/results/%s' % (
      rpc_stubs.AUTOTEST_WEB, job_tag)
